﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace MotionFramework.UIKit
{
    /// <summary>
    /// 默认自动绑定规则辅助器
    /// </summary>
    public class DefaultAutoBindRuleHelper : IAutoBindRuleHelper
    {
        private List<Type> m_ValidComponent = new List<Type>() {
            typeof(CanvasRenderer),
            typeof(ComponentAutoBindTool),
        };

        private string ToFirstUpper(string s)
        {
            char[] a = s.ToCharArray();
            a[0] = char.ToUpper(a[0]);
            return new string(a);
        }

        private bool IsValidComponent(Type componentType)
        {
            return m_ValidComponent.Contains(componentType);
        }

        private bool IsTransformComponent(Type componentType)
        {
            return componentType.IsSubclassOf(typeof(Transform));
        }

        public bool IsValidBind( Transform target, List<string> filedNames, List<string> componentTypeNames)
        {
            var name = ToFirstUpper(target.name);
            var components = target.GetComponents<Component>();
            var componentCount = components.Length;
            foreach (var component in components)
            {
                var componentType = component.GetType();
                var componentName = componentType.Name;

                // 无效组件
                if (IsValidComponent(componentType))
                    continue;

                // 具有两个以上组件就不需要 Transform 了
                if (IsTransformComponent(componentType) && componentCount > 2)
                    continue;

                // RectTransform 强行替换 Transform
                if (IsTransformComponent(componentType))
                    componentName = typeof(Transform).Name;
                
                var fieldName = $"m_{name}{componentName}";
                filedNames.Add(fieldName);
                componentTypeNames.Add(componentName);
            }

            return componentTypeNames.Count > 0;
        }
    }
}
